package com.atguigu.com.bio;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/3
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
//        创建线程池
//        如果有客户端连接，就创建一个线程，与之通信
        ExecutorService newCachedThreadPool = Executors.newCachedThreadPool();
//        创建serverSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");
        while (true) {
//            阻塞，一直监听是否有新客户端的连接请求
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
//          连接到一个客户端，就创建一个线程
            newCachedThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName());
                    handler(socket);
                }
            });
        }
    }

    //    编写一个handler方法，和客户端通信
    public static void handler(Socket socket) {
        try {
            byte[] bytes = new byte[1024];
//        通过socket获取输入流
            InputStream inputStream = socket.getInputStream();
            while (true) {
//               阻塞，一直等待客户端发送数据，虽然简单但是耗资源
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read));
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("close io");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
